package com.ndp.fb.walle.business.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ectemplate.ParseElementResultStatus;
import com.ndp.fb.model.business.vo.ectemplate.EcElementFilterParam;
import com.ndp.fb.rdb.api.EcColorTypeRdbService;
import com.ndp.fb.rdb.api.EcElementStyleRdbService;
import com.ndp.fb.rdb.api.EcProductLogoRdbService;
import com.ndp.fb.rdb.api.EcTemplateProductLogosRdbService;
import com.ndp.fb.rdb.model.EcTemplate;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.ectemplate.EcColorType;
import com.ndp.fb.rdb.model.ectemplate.EcElementStyle;
import com.ndp.fb.rdb.model.ectemplate.EcProductLogo;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateElementStyle;
import com.ndp.fb.storage.StorageService;
import com.ndp.fb.util.*;
import com.ndp.fb.walle.business.EcElementStyleService;
import com.ndp.fb.walle.business.EcProductElementStyleGroupService;
import com.ndp.fb.walle.business.EcProductLogoService;
import com.ndp.fb.walle.business.EcTemplateElementStyleService;
import com.ndp.fb.walle.model.bo.ectemplate.ColorGroup;
import com.ndp.fb.walle.model.bo.ectemplate.EcProductLogoResult;
import com.ndp.fb.walle.model.bo.ectemplate.ParseElementResult;
import com.ndp.fb.walle.model.bo.ectemplate.StyleGroup;
import com.ndp.fb.walle.util.ZipUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Created by sisi.chen on 2016/7/5.
 */
@Component
public class EcProductLogoServiceImpl implements EcProductLogoService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Reference
    private EcElementStyleRdbService ecElementStyleRdbService;

    @Reference
    private EcColorTypeRdbService ecColorTypeRdbService;

    @Autowired
    private StorageService storageService;

    @Reference
    private EcProductLogoRdbService ecProductLogoRdbService;

    @Reference
    private EcTemplateProductLogosRdbService ecTemplateProductLogosRdbService;

    @Autowired
    private EcElementStyleService ecElementStyleService;

    @Autowired
    private EcProductElementStyleGroupService ecProductElementStyleGroupService;

    @Autowired
    private EcTemplateElementStyleService ecTemplateElementStyleService;

    @Override
    public List<ParseElementResult> upload(Long templateId, Long productId, List<MultipartFile> fileList, String realPath, User user) {
        if (CollectionUtils.isEmpty(fileList)){
            return null;
        }

        String folder = realPath + System.getProperty("file.separator") + "uploadlogo" + System.getProperty("file.separator") + UUID.randomUUID().toString();
        List<ParseElementResult> parseElementResults = new ArrayList<>();
        for (MultipartFile file : fileList){
            ParseElementResult parseElementResult = new ParseElementResult();
            parseElementResult.setSuccess(true);
            try {
                String fileName = file.getOriginalFilename();
                String endType = fileName.substring(fileName.lastIndexOf(".") + 1);
                if (!"zip".equals(endType.toLowerCase())) {
                    continue;
                }
                //否则解压
                //一、把前端传入的zip包  解压成文件夹形式
                InputStream input = file.getInputStream();
                ZipUtil.unzip(input, folder);

                //解压完zip 开始解析zip中的文件
                List<EcElementStyle> ecElementStyles = ecElementStyleRdbService.findAll();
                List<EcColorType> ecColorTypes = ecColorTypeRdbService.findAll();
                Map<String, EcElementStyle> ecElementStyleMap = ecElementStyles.stream().filter(i -> StringUtil.isNotEmpty(i.getCode())).collect(Collectors.toMap(EcElementStyle::getCode, (p) -> p));
                Map<String, Long> ecColorTypeMap = ecColorTypes.stream().filter(i -> StringUtil.isNotEmpty(i.getName())).collect(Collectors.toMap(EcColorType::getName, EcColorType::getId));
                Map<String, String> logoContextMap = new HashMap<>();
                Map<String, String> elementShowImgMap = new HashMap<>();
                //存储样式组与Logo的关系  每个模板下各站点只能关联5个样式组的logo（本质上一个模本只能关联5组样式） 多余样式组下的logo就先不传了，提示用户
                Map<Integer, Map<String, EcProductLogo>> ecProductLogoGroupMap = new HashMap<>();
                //存储logo解析过程当中存在的问题logo，用于返回前端
                Map<String, List<String>> errorResults = new HashMap<>();

                //解析zip
                parseLogoZip(productId, folder, ecElementStyleMap, ecColorTypeMap,
                        logoContextMap, elementShowImgMap, ecProductLogoGroupMap, errorResults);

                //存储模板与样式组 产品与样式组的关系,并获取待存储的logo（如果上传了5个以外的样式组，那么剩余的样式组则不能上传，提示给用户）
                Map<String, EcProductLogo> needSaveEcProductLogoMap = saveGroupInfo(templateId, productId, ecProductLogoGroupMap);

                //补全Logo的预览图片和context 保存logo入库
                saveLogos(productId, user, logoContextMap, needSaveEcProductLogoMap, elementShowImgMap);

                //将剩余的未上传的样式组信息返回给前端，提示用户每个模板只能关联5个样式组（表意元素和logo的样式组是相同的概念）
                if (!CollectionUtils.isEmpty(ecProductLogoGroupMap)){
                    //todo 提示用户每个模板只能关联5个样式组（表意元素和logo的样式组是相同的概念）
                    List<String> fileNames = new ArrayList<>();
                    errorResults.put(ParseElementResultStatus.style_group_too_much.getStatus(), fileNames);
                }

                if (!CollectionUtils.isEmpty(errorResults)){
                    //存在错误的logo
                    parseElementResult.setSuccess(false);
                    parseElementResult.setErrors(errorResults);

                }
            } catch (Exception e){
                logger.error(e.getMessage(), e);
                parseElementResult.setSuccess(false);
            } finally {
                //删除文件
                parseElementResults.add(parseElementResult);
                try {
                    File upFile = new File(folder);
                    if (upFile.exists()){
                        upFile.delete();
                    }
                } catch (Exception e){
                    logger.error(e.getMessage(), e);
                }
            }
        }

        return parseElementResults;
    }

    private Map<String,EcProductLogo> saveGroupInfo(Long templateId, Long productId,
                                                    Map<Integer, Map<String, EcProductLogo>> ecProductLogoGroupMap) {
        Map<String, EcProductLogo> needSaveLogos = new HashMap<>();
        if (null == templateId){
            //如果给站点上传logo时，未指定模板，则不限制上传的样式组
            for (Map.Entry<Integer, Map<String, EcProductLogo>> temp : ecProductLogoGroupMap.entrySet()){
                needSaveLogos.putAll(temp.getValue());
                //存储站点和样式组的关系
                ecProductElementStyleGroupService.saveNew(productId, temp.getKey());
            }
            //释放资源
            ecProductLogoGroupMap.clear();
        } else {
            //如果给站点上传logo时，指定了模板，则需要限制上传的样式组（一个模板只能关联5个样式组）
            //将当前上传的logo所属的样式组，与模板相关联;并返回可保存的样式组
            Set<Integer> canSavestyleGroups = ecTemplateElementStyleService.bindNewTemplateElementStyleGroups(templateId, ecProductLogoGroupMap.keySet());
            if (!CollectionUtils.isEmpty(canSavestyleGroups)){
                for (Integer canSavestyleGroup : canSavestyleGroups){
                    //存储站点和样式组的关系
                    ecProductElementStyleGroupService.saveNew(productId, canSavestyleGroup);
                    needSaveLogos.putAll(ecProductLogoGroupMap.remove(canSavestyleGroup));
                }
            }
        }
        return needSaveLogos;
    }

    private void parseLogoZip(Long productId, String logoZipDir, Map<String, EcElementStyle> ecElementStyleMap, Map<String, Long> ecColorTypeMap,
                              Map<String, String> logoContextMap, Map<String, String> elementShowImgMap,
                              Map<Integer, Map<String, EcProductLogo>> ecProductLogoMap, Map<String, List<String>> errorResults) {
        File zipfile = new File(logoZipDir);
        File[] files = zipfile.listFiles();

        List<File> directories = new ArrayList<>();
        for (File logoFile : files){
             try {
                 // 标准是 png（Logo） 和 json
                 if (logoFile.isFile()){
                     String currentFileName = logoFile.getName();
                     if(currentFileName.endsWith(".json")) {
                         JSONArray contexts = JSON.parseArray(FileUtils.readFileToString(logoFile));
                         if(contexts != null && contexts.size() > 0) {
                             for(int m = 0; m < contexts.size(); m++) {
                                 JSONObject obj = (JSONObject) contexts.get(m);
                                 logoContextMap.put(obj.get("code").toString(), obj.toJSONString());
                             }
                         }
                     } else if(currentFileName.startsWith("00000_")) {
                         String elementShowName = ZipUtil.getFileNameNoEx(currentFileName.replaceAll("00000_", ""));
                         String code = UUID.randomUUID().toString();
                         String elementShowImgPath = storageService.storeLogoAsPublic(code, logoFile, currentFileName);
                         elementShowImgMap.put(elementShowName, elementShowImgPath);
                     } else {
                         if (currentFileName.endsWith(".png")){
                             //解析Logo元素
                             ParseElementResultStatus parseElementResultStatus =
                             parseLogo(productId, ecElementStyleMap, ecColorTypeMap, ecProductLogoMap, logoFile);

                             if (parseElementResultStatus != ParseElementResultStatus.success){
                                 List<String> fileNams = errorResults.get(parseElementResultStatus.getStatus());
                                 if (null == fileNams){
                                     fileNams = new ArrayList<>();
                                     errorResults.put(parseElementResultStatus.getStatus(), fileNams);
                                 }
                                 fileNams.add(logoFile.getName());
                             }
                         }
                     }
                 } else if(logoFile.isDirectory()){
                     directories.add(logoFile);
                 } else {
                     ;
                 }
             } catch (Exception e){
                 logger.error(e.getMessage(), e);
             }
        }
        for (File  directory : directories){
            //解析目录
            parseLogoZip(productId, directory.getAbsolutePath(), ecElementStyleMap, ecColorTypeMap, logoContextMap, elementShowImgMap, ecProductLogoMap, errorResults);
        }
    }

    private void saveLogos(Long productId, User user, Map<String, String> logoContextMap, Map<String, EcProductLogo> ecProductLogoMap, Map<String, String> elementShowImgMap) {
        //补全Logo的预览图片和context（用于绘图）
        String key;
        String previewUrl;
        EcProductLogo logoT;
        String context;
        List<EcProductLogo> ecProductLogos = new ArrayList<>();
        for (Map.Entry<String, EcProductLogo> logo : ecProductLogoMap.entrySet()){
            key = logo.getKey();
            logoT = logo.getValue();
            previewUrl = elementShowImgMap.get(key);
            if (null == previewUrl){
                previewUrl = logoT.getElementImg();
            }
            logoT.setElementPreview(previewUrl);

            context = logoContextMap.get(key);
            if (null != context){
                logoT.setElementContext(context.replaceAll("#" + key, logoT.getElementImg()));
            }

            logoT.setProductId(productId);
            logoT.setUserId(user.getTicket());
            logoT.setOrgId(user.getOrgId());
            ecProductLogos.add(logoT);
        }

        //批量保存Logo
        if(ListUtil.isNotEmpty(ecProductLogos)) {
            ecProductLogoRdbService.batchSave(ecProductLogos);
        }
    }

    private ParseElementResultStatus parseLogo(Long productId, Map<String, EcElementStyle> ecElementStyleMap, Map<String, Long> ecColorTypeMap,
                              Map<Integer, Map<String, EcProductLogo>> ecProductLogoGroupMap,
                              File logoFile) throws IOException {
        String currentFileName = logoFile.getName();
        String elementName = ZipUtil.getFileNameNoEx(currentFileName).toUpperCase();

        String[] elementNameArr = elementName.split(CommonConstants.SYMBOL_UNDERLINE);
        boolean nameOk = verifyName(elementNameArr, ecColorTypeMap);
        if (!nameOk){
            return ParseElementResultStatus.invalid_name;
        }

        //校验站点下名称是否重复，如果重复则认为该logo在该站点已经传输过
        List<EcProductLogo> ecProductLogos = ecProductLogoRdbService.findByProductIdAndElementName(productId, elementName);
        if (!CollectionUtils.isEmpty(ecProductLogos)){
            return ParseElementResultStatus.duplication;
        }

        //根据文件名称进行解析
        Long colorType = ecColorTypeMap.get(elementNameArr[2].toLowerCase());
        EcProductLogo ecProductLogo = new EcProductLogo();
        ecProductLogo.setElementName(elementName);
        ecProductLogo.setIsDelete(0);
        ecProductLogo.setCreateTime(new Date().getTime());
        ecProductLogo.setElementColorTypeId(colorType);

        // 可能是新的样式 如果是新的样式需要新建再绑定样式 方便扩充
        EcElementStyle elementStyle = ecElementStyleMap.get(elementNameArr[1].toUpperCase());
        if (null == elementStyle) {
            //新的样式
            String elementStyleCode = elementNameArr[1];
            elementStyle = ecElementStyleService.saveNewElementStyle(elementStyleCode,Integer.parseInt(elementStyleCode.substring(1, elementStyleCode.length())));

        }
        ecProductLogo.setElementStyleId(elementStyle.getId());
        ecProductLogo.setElementStyleGroupId(elementStyle.getStyleGroup());

        ecProductLogo.setMajor("F".equals(elementNameArr[1].substring(0, 1).toUpperCase()) ? true : false);
        ecProductLogo.setParentCode(elementNameArr[0].substring(0, 3).toUpperCase());
        ecProductLogo.setElementCode(elementNameArr[0]);

        //上传Logo
        String code = UUID.randomUUID().toString();
        String imgPath = storageService.storeLogoAsPublic(code, logoFile, currentFileName);
        ecProductLogo.setElementImg(imgPath);

        ecProductLogo.setCreateTime(new Date().getTime());

        //获取当前当时组下对应的新Logo
        Map<String, EcProductLogo> ecProductLogoMap = ecProductLogoGroupMap.get(elementStyle.getStyleGroup());
        if (null == ecProductLogoMap){
            ecProductLogoMap = new HashMap<>();
            ecProductLogoGroupMap.put(elementStyle.getStyleGroup(), ecProductLogoMap);
        }
        //将新Logo先缓存起来
        ecProductLogoMap.put(elementName.toUpperCase(), ecProductLogo);

        return ParseElementResultStatus.success;
    }

    private boolean verifyName(String[] elementNameArr, Map<String, Long> ecColorTypeMap){
        int nameLength = elementNameArr.length;
        //a0101p_f01_gold.png
        if (nameLength != 3 ){
            //还需要丰富名称的校验
            //todo 应该要抛出文件名错误的信息
            return false;
        }

        //目前logo只支持一种形式即a0101p
        if (!"A0101P".equals(elementNameArr[0])){
            return false;
        }

        // 元素层级只能用 F、S来表示
        String level = elementNameArr[1];
        if (level.length() != 3){
            return false;
        }
        if (!level.startsWith("F") && !level.startsWith("S")){
            return false;
        }
        //一个元素下可能有多个样式 01~99
        try {
             Integer styleGroup =  Integer.valueOf(level.substring(1,2));
        } catch (Exception e){
            logger.error(e.getMessage(), e);
            return false;
        }

        Long colorType = ecColorTypeMap.get(elementNameArr[2].toLowerCase());
        if (null == colorType){
            //todo 应该要抛出文件名错误的信息-颜色错误信息
            return false;
        }
        return true;
    }

    @Override
    public Map<String, EcProductLogo> filter(EcElementFilterParam param) {
        Map<String, EcProductLogo> results = new HashMap<>();
        Long templateId = param.getTemplateId();
        if (null == templateId){
            //按 站点 颜色 过滤
            int major = param.getMajor() != null && param.getMajor() ? 1 : 0;
            List<EcProductLogo> logos = ecProductLogoRdbService.filter(param.getColor(), param.getProductId(), major);
            if (!CollectionUtils.isEmpty(logos)){
                for (EcProductLogo logo : logos){
                    results.put(logo.getElementStyleGroupId().toString(), logo);
                }
            }
        } else {
            //按 模板 站点 颜色 过滤
            int major = param.getMajor() != null && param.getMajor() ? 1 : 0;
            List<EcProductLogo> logos = ecProductLogoRdbService.filterByTemplate(templateId, param.getColor(), param.getProductId(), major);
            if (!CollectionUtils.isEmpty(logos)){
                for (EcProductLogo logo : logos){
                    results.put(logo.getElementStyleGroupId().toString(), logo);
                }
            }
        }
        return results;
    }

    @Override
    public Pager<EcProductLogoResult> list(Long orgId, Long templateId, String elementColorType, Integer firstResult, Integer sizeNo) {
        Pager<EcProductLogoResult> result = new Pager<>();
        if (null == templateId){
            //未指定模板 查询 所有与样式组关联的站点
            List<EcProductLogo> ecProductLogos = ecProductLogoRdbService.findByElementColorTypeIdPager(elementColorType, orgId, firstResult, sizeNo);
            if (CollectionUtils.isEmpty(ecProductLogos)){
                return result;
            }

            //将返回的logo 按：站点、颜色、样式组进行分组
            List<EcProductLogoResult> results = buildLogos(ecProductLogos, null);

            //查询关联了样式组的总个数
            Long count = ecProductLogoRdbService.countProductByOrgId(orgId);

            //再根据每个站点下的样式组，查询站点关联的模板

            for (EcProductLogoResult ecProductLogoResult : results){
                List<EcTemplate> ecTemplates = ecTemplateElementStyleService.findByStyleGroupIdsAndOrgId(ecProductLogoResult.getStyleGroups(), orgId);
                ecProductLogoResult.setTemplates(ecTemplates);
            }

            result.setTotalSize(count);
            result.setResultList(results);

        } else {
            //指定了模板
            //1、查询模板下关联的样式组
            List<EcTemplateElementStyle> ecTemplateElementStyles = ecTemplateElementStyleService.findByTemplateId(templateId);
            if (CollectionUtils.isEmpty(ecTemplateElementStyles)){
                return result;
            }
            Set<Integer> styleGroups = new HashSet<>();
            boolean isFirst = true;
            String styleGroupIds = "";
            for (EcTemplateElementStyle ecTemplateElementStyle : ecTemplateElementStyles){
                styleGroups.add(ecTemplateElementStyle.getElementStyleGroupId());
                if (!isFirst){
                    styleGroupIds += ",";
                }
                styleGroupIds += ecTemplateElementStyle.getElementStyleGroupId();
                isFirst = false;
            }

            //2、根据样式组 获取关联的站点并且按站点分页，同时获取完站点和模板下的logo
            List<EcProductLogo> ecProductLogos = ecProductLogoRdbService.findByStyleGroupsAndelementColorTypeIdPager(orgId, styleGroupIds,
                    elementColorType, firstResult, sizeNo);
            if (CollectionUtils.isEmpty(ecProductLogos)){
                return result;
            }

            //将返回的logo 按：站点、颜色、样式组进行分组
            List<EcProductLogoResult> results = buildLogos(ecProductLogos, styleGroups);

            //查询模板下关联了站点的总个数
            Long count = ecProductLogoRdbService.countProductByTemplateId(templateId);

            result.setTotalSize(count);
            result.setResultList(results);
        }

        return result;
    }

    private List<EcProductLogoResult> buildLogos(List<EcProductLogo> ecProductLogos, Set<Integer> globalStyleGroups) {
        //3、组织数据按颜色 样式组分组
        Map<Long, EcProductLogoResult> productGroups = new HashMap<>();
        //Map<Long, Map<Integer, Map<String, EcProductLogo>>> productLogos;
        Map<Long, Map<String, Map<Integer, Map<String, EcProductLogo>>>> productGroupsM = new HashMap<>();
        Long productId;
        EcProductLogoResult productLogos;
        String colorName;
        Integer elementStyleGroupId;
        for (EcProductLogo logo : ecProductLogos){
            productId = logo.getProductId();
            //3.1  按站分组
            productLogos = productGroups.get(productId);
            if (null == productLogos){
                productLogos = new EcProductLogoResult();
                productLogos.setProductId(productId);
                productLogos.setProductName(logo.getProductName());
                productLogos.setRelativeTime(logo.getRelativeTime());
                productLogos.setColorGroups(new ArrayList<>());
                productLogos.setStyleGroups(new HashSet<>());
                productGroups.put(productId, productLogos);

                productGroupsM.put(productId, new HashMap<>());
            }
            //3.2 站下按颜色分组
            colorName = logo.getColorName();
            Map<String, Map<Integer, Map<String, EcProductLogo>>> colorGroups =productGroupsM.get(productId);
            Map<Integer, Map<String, EcProductLogo>> colorGroup = colorGroups.get(colorName);
            if (null == colorGroup){
                colorGroup = new HashMap<>();
                colorGroups.put(colorName, colorGroup);

                //给每个颜色占位样式组，保证切换不同颜色时，样式组是对应的
                if (!CollectionUtils.isEmpty(globalStyleGroups)){
                    //对于获取指定模板下的Logo才会传此字段，确保整个模板所有颜色的样式组是全的，一一对应的
                    for (Integer styleGroup : globalStyleGroups){
                        colorGroup.put(styleGroup, null);
                    }
                }
            }

            //3.3 颜色下按样式组分组
            elementStyleGroupId = logo.getElementStyleGroupId();
            Map<String, EcProductLogo> styleGroup = colorGroup.get(elementStyleGroupId);
            if (null == styleGroup){
                styleGroup = new HashMap<>();
                colorGroup.put(elementStyleGroupId, styleGroup);
                //存储站点下支持的样式组 后续需要跟着这个样式组，将站点下每个颜色对应的样式组补全
                productLogos.getStyleGroups().add(elementStyleGroupId);
            }

            //4.最终的logo
            if (logo.getMajor()){
                //主
                styleGroup.put("F", logo);
            } else {
                //辅
                styleGroup.put("S", logo);
            }
        }

        buildResult(productGroups, productGroupsM);
        List<EcProductLogoResult> results = new ArrayList<>(productGroups.values());
        Collections.sort(results);
        return results;

    }

    private void buildResult(Map<Long, EcProductLogoResult> productGroups, Map<Long, Map<String, Map<Integer, Map<String, EcProductLogo>>>> productGroupsM) {
        Set<Integer> productStyleGroups;
        EcProductLogoResult ecProductLogoResult;
        for (Map.Entry<Long, EcProductLogoResult> productLogos: productGroups.entrySet()){
            Long productId = productLogos.getKey();
            ecProductLogoResult = productLogos.getValue();
            //当前站点支持的全部样式组
            productStyleGroups = ecProductLogoResult.getStyleGroups();

            // Map<Long, Map<Long, Map<Integer, Map<String, EcProductLogo>>>> productGroupsM
            //构造产品下的颜色组
            List<ColorGroup> colorGroupBs = new ArrayList<>();
            Map<String, Map<Integer, Map<String, EcProductLogo>>> colorGroups = productGroupsM.get(productId);
            for (Map.Entry<String, Map<Integer, Map<String, EcProductLogo>>> colorGroup: colorGroups.entrySet()){
                ColorGroup colorGroupB = new ColorGroup();
                colorGroupB.setColorName(colorGroup.getKey());
                colorGroupBs.add(colorGroupB);

                //构造颜色组下的样式组
                List<StyleGroup> styleGroupBs = new ArrayList<>();
                Map<Integer, Map<String, EcProductLogo>> styleGroups = colorGroup.getValue();
                //根据站点支持的样式组来补全颜色下对应的样式组，确保每个颜色的样式组是一样的，一一对应的
                for (Integer pStyleGroup : productStyleGroups){
                    if (null == styleGroups.get(pStyleGroup)){
                        styleGroups.put(pStyleGroup, new HashMap<>());
                    }
                }

                for(Map.Entry<Integer, Map<String, EcProductLogo>> styleGroup: styleGroups.entrySet()){
                    StyleGroup styleGroupB = new StyleGroup();
                    styleGroupB.setStyleGroupId(styleGroup.getKey());
                    styleGroupB.setLogos(styleGroup.getValue());
                    styleGroupBs.add(styleGroupB);
                }
                //按样式组进行排序:保证每个颜色下的样式组相同且顺序一致的
                Collections.sort(styleGroupBs);
                colorGroupB.setStyleGroups(styleGroupBs);
            }

            ecProductLogoResult.setColorGroups(colorGroupBs);
        }
    }
}
